<template>
	<view class="container">
		<!-- 顶部时间栏 -->
		<view class="time-header" :style="{ background: t('color1') }">
			<scroll-view scroll-x class="time-bar" :scroll-left="scrollLeft">
				<view v-for="(item, index) in timeList" :key="index" class="time-item"
					:class="{ active: currentTimeIndex === index }"
					:style="{ color: currentTimeIndex === index ? t('color1') : '' }" @tap="switchTime(item, index)">

					<!-- 时间显示 -->
					<text class="status countdown" v-if="shouldShowCountdown(item)" :style="{ color: t('color2') }">
						{{ formatCountdown(item.end_time) }}
					</text>
					<text v-else class="time">{{ item.showtime }}</text>

					<!-- 状态显示 -->
					<text class="status" v-if="isActivityEnded(item)">活动已结束</text>
					<text class="status" v-if="item.active == 0">未开始</text>
					<text class="status" v-if="isActivityRunning(item)" :style="{ color: t('color2') }">进行中</text>
				</view>
			</scroll-view>
		</view>

		<!-- 分类标签栏 -->
		<scroll-view scroll-x class="category-bar" :scroll-left="scrollPriceLeft">
			<text class="category-item" v-for="(item, index) in price_list" :key="index"
				:class="{ active: currentPriceIndex === index }"
				:style="{ color: currentPriceIndex === index ? t('color1') : '' }" @tap="switchPrice(item, index)">{{
					item.price_min }}</text>

		</scroll-view>

		<!-- 商品列表 -->
		<scroll-view scroll-y class="product-list" v-if="items.length > 0">
			<view v-for="item in items" :key="item.id" class="product-item">
				<view class="product-image">
					<image :src="item.pic" mode="aspectFill" />
					<view v-if="item.tag" class="product-tag" :style="{ background: t('color2') }">{{ item.tag }}</view>
				</view>
				<view class="product-info">
					<view class="product-title">{{ item.name }}</view>
					<view class="limit-time">
						<text>库存{{ item.stock }}件</text>
						<text v-if="timeList[currentTimeIndex].active == 1">已售{{ item.sales }}件</text>
						<!-- <text>{{item.limitTime}}开抢</text> -->
					</view>
					<!-- <view class="user-count" v-if="item.userCount">
						<image src="/static/img/user-icon.png" mode="aspectFit" class="user-icon" />
						<text>{{item.userCount}}人已约</text>
					</view> -->
					<view class="progress-bar-container" v-if="timeList[currentTimeIndex].active == 1">
						<view class="progress-bar">
							<view class="progress-inner"
								:style="{ width: item.salepercent + '%', background: t('color1') }"
								:class="{ 'almost-sold': item.salepercent > 80 }"></view>
						</view>
						<text class="progress-text" :class="{ 'warning': item.salepercent > 80 }">
							{{ item.salepercent > 80 ? '即将售罄' : '已售' + item.salepercent + '%' }}
						</text>
					</view>
					<view class="price-row">
						<view class="price-container" :style="{ color: t('color1') }">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ item.sell_price }}</text>
						</view>
						<view class="original-price">¥{{ item.market_price }}</view>
						<!-- <button class="buy-btn" :style="{background:t('color1')}" :class="{ 'subscribed': item.is_subscribe === 1 }"
							@click="toggleSubscribe(item)">
							{{ item.is_subscribe === 1 ? '已订阅' : '订阅' }}
						</button> -->
						<button class="buy-btn" :style="{ background: t('color1') }" :class="{
							'subscribed': item.is_subscribe === 1,
							'buying': timeList[currentTimeIndex].active === 1
						}" @click.stop="handleButtonClick(item)" :disabled="submitDisabled">
							{{
								timeList[currentTimeIndex].active === 1 ? '去抢购' :
									(item.is_subscribe === 1 ? '已订阅' : '订阅')
							}}
						</button>
					</view>

				</view>
			</view>
		</scroll-view>
		<nodata v-else></nodata>
	</view>
</template>

<script>
var app = getApp();
export default {
	data() {
		return {
			currentTimeIndex: 0,
			currentPriceIndex: 0,
			scrollLeft: 0,
			scrollPriceLeft: 0,
			datalist: [],
			nomore: false,
			nodata: false,
			page: 1,
			pageSize: 10,
			hasMore: true,
			isLoading: false,
			timeList: [],
			price_list: [],
			timer: null,
			items: [],
			submitDisabled: false,
			queryParams: {
				seckill_date: '',
				seckill_time: '',
				price_min: '',
				price_max: ''
			}
		}
	},
	onLoad() {
		this.getdata();
		// this.getlist()
		this.timer = setInterval(() => {
			this.timeList.forEach(item => {
				if (item.active === 1) {

					this.$forceUpdate();
				}
			});
		}, 1000);
	},
	onPullDownRefresh: function () {
		this.getlist(true);
		uni.stopPullDownRefresh();
	},
	onUnload() {
		// 组件销毁时清除定时器
		if (this.timer) clearInterval(this.timer);
	},
	methods: {
		getdata() {
			const that = this;
			app.get('Seckill/index', {}, function (res) {
				that.timeList = res.navlist;
				that.price_list = res.set.price_list;
				that.loaded();
				// 初始化默认查询参数（选中第一个时间和价格）
				if (res.navlist.length > 0) {
					that.queryParams.seckill_date = res.navlist[0].seckill_date;
					that.queryParams.seckill_time = res.navlist[0].seckill_time;
				}
				if (res.set.price_list.length > 0) {
					that.queryParams.price_min = res.set.price_list[0].price_min;
					that.queryParams.price_max = res.set.price_list[0].price_max;
				}

				// 首次加载商品列表
				that.getlist();
			});
		},
		getlist(isPullRefresh = false) {
			const that = this;
			app.get('Seckill/getprolist', {
				seckill_date: this.queryParams.seckill_date,
				seckill_time: this.queryParams.seckill_time,
				price_min: this.queryParams.price_min,
				price_max: this.queryParams.price_max,
			}, function (res) {
				that.loaded();
				if (res.status == 1) {
					that.items = res.data;
					if (res.data.length == 0) {
						that.nodata = true;
					}
				} else {
					app.error(res.msg);
				}
				// 如果是下拉刷新，停止刷新动画
				if (isPullRefresh) {
					uni.stopPullDownRefresh();
				}
			});
		},
		handleButtonClick(item) {
		    let seckill_date = this.queryParams.seckill_date;
		    let seckill_time = this.queryParams.seckill_time;
		
		    if (this.timeList[this.currentTimeIndex].active === 1) {
		        uni.navigateTo({
		            url: `/pages/shop/product?id=${item.id}&seckill_date=${seckill_date}&seckill_time=${seckill_time}&ptype=seckill`
		        })
		    } else {
		        this.toggleSubscribe(item);
		    }
		},
		
		toggleSubscribe(item) {
		    const isSubscribe = item.is_subscribe === 1;
		    const action = isSubscribe ? '取消订阅' : '订阅';
		
		    this.getTmplIds({detail: {item}, isUnsubscribe: isSubscribe});
		},
		
		getTmplIds: function(e) {
		    var that = this;
		    if (that.submitDisabled) return;
		    that.submitDisabled = true;
		    that.loading = true;
		    
		    // #ifdef MP-WEIXIN
		    app.get('Wxtmpl/getTmplIds', {
		        type: 6
		    }, function(res) {
		        that.loading = false;
		        var tmplIds = res.res;
		        if (res.res) {
		            wx.requestSubscribeMessage({
		                tmplIds: tmplIds,
		                complete(authRes) {
		                    that.submitDisabled = false;
		                    // 在这里直接处理订阅逻辑，而不是调用handleSubscribe
		                    const url = 'Seckill/subscribe';
		                    const isUnsubscribe = e.isUnsubscribe;
		                    
		                    app.post(url, {
		                        proid: e.detail.item.id,
		                        seckill_date: that.queryParams.seckill_date,
		                        seckill_time: that.queryParams.seckill_time,
		                        action: isUnsubscribe ? 'unsubscribe' : 'subscribe'
		                    }, res => {
		                        if (res.status == 0) {
		                            e.detail.item.is_subscribe = isUnsubscribe ? 0 : 1;
		                            app.success(res.msg || `${isUnsubscribe ? '取消订阅' : '订阅'}成功`);
		                        } else {
		                            app.error(res.msg || `${isUnsubscribe ? '取消订阅' : '订阅'}失败`);
		                        }
		                    });
		                }
		            });
		        } else {
		            that.submitDisabled = false;
		            // 获取模板失败也执行订阅
		            that.handleSubscribe(e.detail.item, e.isUnsubscribe);
		        }
		    });
		    // #endif
		    
		    // #ifdef H5
		    that.loading = false;
		    that.submitDisabled = false;
		    that.handleSubscribe(e.detail.item, e.isUnsubscribe);
		    // #endif
		},
		
		handleSubscribe(item, isUnsubscribe) {
		    const url = 'Seckill/subscribe';
		    
		    app.post(url, {
		        proid: item.id,
		        seckill_date: this.queryParams.seckill_date,
		        seckill_time: this.queryParams.seckill_time,
		        action: isUnsubscribe ? 'unsubscribe' : 'subscribe'
		    }, res => {
		        if (res.status == 0) {
		            item.is_subscribe = isUnsubscribe ? 0 : 1;
		            app.success(res.msg || `${isUnsubscribe ? '取消订阅' : '订阅'}成功`);
		        } else {
		            app.error(res.msg || `${isUnsubscribe ? '取消订阅' : '订阅'}失败`);
		        }
		    });
		},
		switchTime(item, index) {
			this.currentTimeIndex = index;
			this.scrollLeft = index * 100 - 100;
			// 更新查询参数
			this.queryParams.seckill_date = item.seckill_date;
			this.queryParams.seckill_time = item.seckill_time;

			// 重新加载商品列表
			this.getlist();
		},
		switchPrice(item, index) {
			this.currentPriceIndex = index;
			this.scrollPriceLeft = index * 100 - 50;
			// 更新查询参数
			this.queryParams.price_min = item.price_min;
			this.queryParams.price_max = item.price_max;

			// 重新加载商品列表
			this.getlist();
		},
		formatCountdown(endTime) {
			const now = Math.floor(Date.now() / 1000);
			const remaining = endTime - now;

			if (remaining <= 0) return "00:00:00";

			const hours = Math.floor(remaining / 3600);
			const minutes = Math.floor((remaining % 3600) / 60);
			const seconds = remaining % 60;
			const pad = (num) => num.toString().padStart(2, '0');

			return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
		},

		// 判断是否显示倒计时
		shouldShowCountdown(item) {
			return item.active == 1 && !this.isActivityEnded(item);
		},

		// 判断活动是否已结束
		isActivityEnded(item) {
			if (item.active == -1) return true;
			if (item.active == 1) {
				return this.formatCountdown(item.end_time) === "00:00:00";
			}
			return false;
		},

		// 判断活动是否进行中
		isActivityRunning(item) {
			return item.active == 1 && !this.isActivityEnded(item);
		}
	}
}
</script>

<style>
.container {
	background-color: #f5f5f5;
}

.time-header {
	padding: 20rpx 0;
}

.status-text {
	color: #fff;
	font-size: 28rpx;
	padding: 0 20rpx;
	margin-bottom: 10rpx;
}

.time-bar {
	white-space: nowrap;

	padding: 0 20rpx;
}

.time-item {
	display: inline-block;
	width: 200rpx;
	text-align: center;
	padding: 15rpx 0;
	color: rgba(255, 255, 255, 0.8);
	position: relative;
	transition: all 0.3s ease;
	border-radius: 8rpx;
	margin: 0 10rpx;
}

.time-item.active {
	background-color: #fff;
}

.time-item.active::after {
	display: none;
}

.time {
	font-size: 32rpx;
	font-weight: bold;
	display: block;
}

.status {
	font-size: 24rpx;
	display: block;
	margin-top: 4rpx;
	color: inherit;
}


.category-bar {
	white-space: nowrap;
	padding: 20rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.category-item {
	display: inline-block;
	padding: 10rpx 30rpx;
	margin-right: 20rpx;
	font-size: 28rpx;
	color: #333;
}

.category-item.active {
	color: #EA373C;
}

.product-list {
	padding: 20rpx;
}

.product-item {
	display: flex;
	padding: 20rpx;
	background: #fff;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.product-image {
	width: 200rpx;
	height: 200rpx;
	position: relative;
	margin-right: 20rpx;
}

.product-image image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.product-tag {
	position: absolute;
	top: 0;
	left: 0;

	color: #fff;
	font-size: 20rpx;
	padding: 4rpx 8rpx;
	border-radius: 4rpx 0 4rpx 0;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-title {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	text-overflow: ellipsis;
	line-height: 1.4;

}

.limit-time {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 8rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.user-count {
	display: flex;
	align-items: center;
	font-size: 24rpx;
	color: #666;
	margin-bottom: 8rpx;
}

.user-icon {
	width: 24rpx;
	height: 24rpx;
	margin-right: 4rpx;
}

.price-row {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
	margin-top: 10rpx;
}

.price-container {
	color: #ff4444;
}

.price-symbol {
	font-size: 24rpx;
}

.price-value {
	font-size: 36rpx;
	font-weight: bold;
}

.price-unit {
	font-size: 24rpx;
	color: #999;
}

.original-price {
	font-size: 24rpx;
	color: #999;
	text-decoration: line-through;
	margin-left: 10rpx;
	margin-right: auto;
}

.buy-btn {

	color: #fff;
	font-size: 24rpx;
	padding: 0 20rpx;
	height: 48rpx;
	line-height: 48rpx;
	border-radius: 24rpx;
	margin: 0;
}

.buy-btn.disabled {
	background: #ccc;
}

.progress-bar-container {
	display: flex;
	align-items: center;
	margin-top: 10rpx;
}

.progress-bar {
	flex: 1;
	height: 20rpx;
	background: #eee;
	border-radius: 20rpx;
	overflow: hidden;
	margin-right: 10rpx;
}

.progress-inner {
	height: 100%;

	transition: width 0.3s;
}

.progress-inner.almost-sold {
	background: #ff9500;
}

.progress-text {
	font-size: 22rpx;
	color: #999;
}

.progress-text.warning {
	color: #ff9500;
}
</style>